// alliance//receiveAllianceCoupon/index.js
const utils = require('../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    allFlyerId: [],
    flyerList: [],
    createUid: 0,
    staffid: 0,
    windowHeight: 500,
    storeiid: 0,
    CurrentPage: 1,
    loadingMoreHidden: 1,
    isAccredit: false,
    costMoney: 0,
    couponMoney: 0,
    merchants: 0,
    isAuth: true,
    mobile: '',
    hasJJK: true,
    showWxcard: 0
  },

  // 领取传单礼包
  //获取手机号
  getPhoneNumber: function (e) {
    let that = this;
    utils.getMobile(e, function (callback) {
      if (callback) {
        that.receivePackage();
        that.setData({
          mobile: callback
        })
      } else {
        that.showToast({
          title: '请授权手机号',
          mask: true
        })
      }
    });
  },
  receivePackage: function () {
    let that = this;
    let showWxcard = that.data.showWxcard;
    let gradeIds = that.data.allFlyerId;
    gradeIds = gradeIds.join(',');
    wx.showLoading({
      title: '正在领取',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/leaflet/ReceivePackage',
      data: {
        uid: app.globalData.userInfo.Uid,
        shareUid: that.data.createUid,
        gradeIds: gradeIds
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        console.log('传单礼包领取结果', res);
        if (res.data.Code == 0) {
          wx.showToast({
            title: '领取成功',
            mask: true
          })
          wx.reLaunch({
            url: '/merchant/merchants/myCardCoupon/index?tagindex=5&showWxcard=' + showWxcard,
          })
        } else {
          that.checkWrite(res.data.Message);
        }
      },
    })
  },

  // 获取礼包统计数据
  getSaleInfo: function (createUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/leaflet/GetPackageTotal?uid=' + app.globalData.userInfo.Uid + '&shareUid=' + createUid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            costMoney: res.data.Data.CardMoney,
            couponMoney: res.data.Data.CouponMoney,
            merchants: res.data.Data.StaffCount,
            allFlyerId: res.data.Data.GradeIds
          })
        }
      }
    })
  },

  // 获取传单商家及礼包
  getPackageList: function (createUid) {
    let that = this;
    wx.showLoading({
      title: '努力加载中......',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetPackageList?uid=' + app.globalData.userInfo.Uid + '&shareUid=' + createUid + '&page=' + that.data.CurrentPage,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          let addedMerlist = res.data.Data.Items;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.addedMerlist
            addedMerlist = preGoods.concat(addedMerlist);
          }
          for (let i = 0; i < addedMerlist.length; i++) {
            if (addedMerlist[i].staff.Avater) {
              addedMerlist[i].staff.Avater = utils.formatAvater(addedMerlist[i].staff.Avater, 'https://static.711688.net.cn/upload/card/source/');
            }
            let carditems = addedMerlist[i].CardItemList;
            if (carditems.length > 0) {
              for (let j = 0; j < carditems.length; j++) {
                var detailpics = carditems[j].DetailPics;
                carditems[j].showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  carditems[j].showDetailPics = list[0];
                }
              }
            }
            let coupons = addedMerlist[i].CouponTypeList;
            if (coupons.length > 0) {
              for (let j = 0; j < coupons.length; j++) {
                var detailpics = coupons[j].DetailPics;
                coupons[j].showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  coupons[j].showDetailPics = list[0];
                }
              }
            }
            let card = addedMerlist[i].Card;
            if (card) {
              card.Discount = card.Discount * 0.1;
              card.Discount = card.Discount.toFixed(1);
              var detailpics = card.DetailPics;
              if (detailpics) {
                card.showDetailPics = '';
                var list = [];
                if (detailpics != '') {
                  var newDetailPics = detailpics.split(",");
                  for (let k = 0; k < newDetailPics.length; k++) {
                    list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                  }
                  card.showDetailPics = list[0];
                }
              }

            }
          }
          that.setData({
            flyerList: addedMerlist,
            loadingMoreHidden: res.data.Data.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 查看单个商家活动
  toStaffDetail: function (e) {
    let flyerid = e.currentTarget.dataset.flyerid;
    let allFlyerId = this.data.allFlyerId;
    wx.navigateTo({
      url: '../oneStaffFlyer/index?flyerid=' + flyerid + '&allFlyerId=' + allFlyerId,
    })
  },

  //是否已经领取玖玖卡
  getJJKInfo: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardExists?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (!res.data.Data) {
            that.setData({
              hasJJK: false
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('领取传单礼包入口参数', options);
    let that = this;
    let params = decodeURIComponent(options.scene);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let plist = '';
      let param = params.match(/p-(\S*)/)[1];//参数
      plist = param.split('_');
      that.data.createUid = plist[1];
      that.data.staffid = plist[0];
      wx.setStorageSync('cardId', plist[0]);
      console.log('小程序码参数', plist);
    } else {
      that.data.createUid = options.createUid;
      if (options.id) {
        that.data.staffid = options.id;
        wx.setStorageSync('cardId', options.id);
      }
      if(options.showWxcard){
        that.data.showWxcard = options.showWxcard;
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo && that.data.createUid > 0) {
      that.getJJKInfo()
      that.getPackageList(that.data.createUid);
      that.getSaleInfo(that.data.createUid);
      utils.isAccredit(function (isAccredit) {
        that.setData({
          isAccredit: isAccredit
        })
      });
      if (app.globalData.userInfo.Mobile) {
        that.setData({
          mobile: app.globalData.userInfo.Mobile
        })
      }
    } else {
      setTimeout(function () {
        that.onShow();
      }, 1000)
    }

  },

  loadMore: function () {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getPackageList(that.data.createUid);
    } else {
      return
    }
  },
  //填写判断
  checkWrite: function (str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  }
})